package com.aoxon.cargo.adapter;

import java.util.List;

import uk.co.senab.photoview.PhotoView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.util.ImageUtil;

public class PubPicturePagerAdapter extends PagerAdapter {

	private List<Picture> pictures;
	private LayoutInflater layoutInflater;
	private FileLoader imageLoader = new FileLoader(800, 800, false);

	public PubPicturePagerAdapter(Activity activity, List<Picture> pictures) {
		this.pictures = pictures;
		this.layoutInflater = LayoutInflater.from(activity);
	}

	@Override
	public int getCount() {
		return pictures.size();
	}

	@Override
	public View instantiateItem(ViewGroup container, int position) {
		
		RelativeLayout viewPagerItem = (RelativeLayout) layoutInflater.inflate(
				R.layout.pub_view_pager_picture_item, null);
		
		PhotoView photoView = (PhotoView) viewPagerItem
				.findViewById(R.id.pvPagerItem);
		
		ProgressBar progressBar = (ProgressBar) viewPagerItem
				.findViewById(R.id.pbPagerItem);
		
		TextView tvPicIndex = (TextView) viewPagerItem
				.findViewById(R.id.tvPicIndex2);
		
		tvPicIndex.setText("图片数：" + (position + 1) + "/" + pictures.size());
		if (SupCache.fromCamera) {
			Bitmap bitmap;
			try {
				bitmap = ImageUtil.getImageBitmap(pictures.get(position)
						.getPictureUrl(), 480, 480);
				photoView.setImageBitmap(ImageUtil.imageCropToSquare(bitmap));
				progressBar.setVisibility(View.GONE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			String path = pictures.get(position).getPictureUrl() + "l.png";
			imageLoader.displayImage(path, photoView, progressBar, false);
		}
		container.addView(viewPagerItem, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		return viewPagerItem;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}
}
